/*!
    create css by 2020-12-10  kexuemihe  @wang   互动课件 
    现在保存/发布互动视频视频源都是在后台的   然后回写数回写的是前台的互动视频
*/
$(function () {
    window.testUrl = "http://m.kexuemihe.com"; //http://m.kexuemihe.com   //http://139.186.155.167
    // window.onbeforeunload = function () { //如果用户即将离开页面或者关闭窗口时，beforeunload事件将会被触发以进行额外的确认。有些浏览器像Chrome和火狐会忽略返回的字符串取而代之显示浏览器自身的文本，这是为了安全考虑，来保证用户不受到错误信息的误导。
    //     return "There are unsaved changes. Leave now?";
    // };
    /**
     * 当用户选择机构了，则加载对应机构
     */
    let curOrgan = extendLocalStorage.get("curOrgan");
    if (curOrgan) {
        $("#logoInfo").empty().append(`<p style="width: 100%;" id="logoText" org_id=${curOrgan.org_id}>${curOrgan.name}</p>`);
    }
    /**
     * 当用户选择机构了，则加载对应机构
     */
    /**
     * 公共变量
     */
    let selABCD = ['A', "B", 'C', "D"],
        userinfo = extendLocalStorage.get("userinfo"),
        SCArr = [], //存放素材名称的数组
        courseName = '', //课程名称
        courseImgUrl = ''; //课程封面
    // uploadFilesArr = []; //用来解决上传多个视频成功后进行图片地址赋值
    var aliyunUrl = "http://video.mxiaotu.com/";
    /**
     * 互动视频回写   回写的课件实际上 status都是0
     */
    let hrefInfo = location.href.split("id=")[1],
        status = 0; //是发布的编辑  还是保存的课件编辑
    if (hrefInfo) { //如果地址后有id=？？？ 值   则证明用户是互动课件编辑按钮进入的页面，所以是回写页面
        console.log(hrefInfo);
        let courseData = {
            id: hrefInfo
        }
        $.ajax({
            type: "get",
            // url: `${testUrl}/platform/resource/view`,
            url: `${testUrl}/S9vC7rYOo4.php/small/resource/edit`,  //后台获取信息的接口
            headers: {
                token: userinfo.token
            },
            data: courseData,
            success: function (res) {
                console.log(res);
                data = res.data.context;
                status = res.data.status;
                $(".personal strong").text(res.data.title);
                //剧情素材渲染s
                SCArr = res.data.context.SCArr;
                /**
                 * 更快的dom操作方法
                 */
                let eleArr = `<ul id="materialStore">`;
                $.each(SCArr, function (i, item) {
                    if (item.fileUrl.length < 30) {
                        eleArr += `
                        <li class="dragStyle" playUrl="${item.playUrl}" materialId="${item.materialId}" isImage="${item.fileUrl}">
                            <div class="conBox">
                                <img draggable="false" style="width: 43%;height: 70%;" src=${item.fileUrl}>
                            </div>
                            <p>${item.fileName}</p>
                </li>`;
                    } else {
                        eleArr += `
                        <li class="dragStyle" playUrl="${item.playUrl}" materialId="${item.materialId}" isImage="${item.fileUrl}">
                            <div class="conBox">
                                <img draggable="false" src=${item.fileUrl}>
                            </div>
                            <p>${item.fileName}</p>
                </li>`
                    }
                });
                eleArr += `</ul>`;
                $("#materialStore").replaceWith(eleArr);
                /**
                 * 更快的dom操作方法
                 */
                dragMaterial();
                // 封面内容渲染
                courseName = res.data.title;
                courseImgUrl = res.data.cover;
                $("#courseName").val(courseName);
                $(".cover label img").attr({
                    src: courseImgUrl,
                    width: '100%',
                    height: "100%",
                });
                $(".cover label").attr({
                    background: "#F2FBFF"
                });
                // 树形图渲染
                graph.data(data);
                graph.render();
                graph.fitCenter();
            }
        });
    }
    /**
     * 互动视频回写
     */
    /*
    树形图加载开始
    // ---------------------------------------------------------------------------------
    //  技术栈  ：　1.antv里的G6引擎（svg渲染 +　自定义dom节点）制作基本ui样式。
    //             2.svg渲染规定不能使用G6中内置的事件api，要在创建自定义dom节点时，在标签的行内加入事件信息。
    //             3.行内事件不能满足交互要求，但是外部能获取到自定义dom元素，但是不能对其添加事件。（解决方法：给svg标签添加事件，使用事件委托到具体的html元素就可以了）
    // --------------------------------------------------------------------------------
    */
    let data = {
        id: 'root',
        label: '拖拽素材至此', //素材名称
        imgUrl: "", // 素材封面
        tip: "请选择", //绑定的素材名称  
        answerName: "root", //树叉分支的展示内容
        materialId: "", // 树叉绑定的素材 id （此id对应上传到阿里云服务器的id）用来获取阿里云上传内容信息 
        // playUrl: "http://video.mxiaotu.com/sv/38c938d2-1762821c970/38c938d2-1762821c970.mp4", //当点击预览互动视频时，直接调用这个地址
        pictureStop: 0, //画面暂停组件  0不启动该组件  1启动该组件
        addFuUrl: "./images/hao.png",
        TPmaterialId: '', //备课教案绑定得素材id
        TPplayUrl: '', //备课教案绑定得素材播放地址
        TPimgUrl: "", //备课教案绑定得素材封面
        TPTip: "", //备课教案绑定的素材名称  
        noComponent: true, //  无组件且只有一个分支时，则自动播放下个视频
        interGame: { //互动游戏的参数，封面图则保存在了imgUrl  互动名称保存给了label
            _interId: "",
            _interType: ""
        }
        // labelInfo: { //标注信息
        //     // labelBackgroundImg: "", //背景图片
        //     // labelA: {
        //     //     x: "", //定位位置
        //     //     y: "",
        //     //     textInfo: ""
        //     // },
        //     // labelB: {
        //     //     x: "", //定位位置
        //     //     y: "",
        //     //     textInfo: ""
        //     // },
        //     // labelC: {
        //     //     x: "", //定位位置
        //     //     y: "",
        //     //     textInfo: ""
        //     // },
        //     // labelD: {
        //     //     x: "", //定位位置
        //     //     y: "",
        //     //     textInfo: ""
        //     // },
        // }
    };
    // const grid = new G6.Grid(); //网格插件
    const EXPAND_ICON = function EXPAND_ICON(x, y, r) {
        return [
            ['M', x - r, y - r],
            ['a', r, r, 0, 1, 0, r * 2, 0],
            ['a', r, r, 0, 1, 0, -r * 2, 0],
            ['M', x + 2 - r, y - r],
            ['L', x + r - 2, y - r],
            ['M', x, y - 2 * r + 2],
            ['L', x, y - 2],
        ];
    };
    G6.registerNode(
        'icon-node', {
            options: {

            },
            draw(cfg, group) {
                const styles = this.getShapeStyle(cfg);
                const {
                    labelCfg = {}
                } = cfg;

                const w = styles.width;
                const h = styles.height;
                const keyShape = group.addShape('dom', {
                    attrs: {
                        ...styles,
                        x: -w / 2,
                        y: -h / 2,
                        //  title="${cfg.answerName}" 
                        html: `<section materialId="${cfg.materialId}" playUrl="${cfg.playUrl}" id=${cfg.id} tip="${cfg.tip}"><img draggable="false" class="showImg" src="${cfg.imgUrl}" alt=""><span>${cfg.label}<span></section>`
                    },
                    capture: true,
                });
                // 加号
                group.addShape('dom', {
                    attrs: {
                        width: 22,
                        height: 22,
                        x: 50,
                        y: -11,
                        html: ` <div id="addFu" style="background: #FFFFFF url(${cfg.addFuUrl}) no-repeat 50% 45%;border-radius: 50%;background-size: 10px;"  TPmaterialId="${cfg.TPmaterialId}" TPTip="${cfg.TPTip}" TPplayUrl="${cfg.TPplayUrl}" TPimgUrl="${cfg.TPimgUrl}"></div>`,
                    },
                    capture: true,
                    draggable: true,
                    name: 'add-item',
                });
                // 移入加号显示的操作栏
                group.addShape('dom', {
                    attrs: {
                        width: 110,
                        height: 50,
                        x: 20,
                        y: 10,
                        radius: 10,
                        // 传入 DOM 的 htmldisplay:none;height:100%;
                        html: `<div class="showOpt">
                                        <p id="createModule">创建剧情模块</p>
                                        <p id="delModule">删除剧情模块</p>
                                    </div>`,
                    },

                    // <p id="createJumpModule">创建跳转分支</p>
                    capture: true,
                    draggable: true,
                    name: "htmlOPT",
                });

                return keyShape;
            },
        },
        'rect',
    );
    const defaultLayout = {
        type: 'compactBox',
        direction: 'LR',
        getId: function getId(d) {
            return d.id;
        },
        getHeight: function getHeight() {
            return 16;
        },
        getWidth: function getWidth() {
            return 16;
        },
        getVGap: function getVGap() {
            return 40;
        },
        getHGap: function getHGap() {
            return 70;
        },
    };
    const container = document.getElementById('container');
    const width = container.scrollWidth;
    const height = container.scrollHeight || 500;
    // const minimap = new G6.Minimap({
    //     size: [150, 100],
    // });
    const graph = new G6.TreeGraph({
        container: 'container',
        width,
        height,
        renderer: "svg",
        // linkCenter: true,
        // plugins: [minimap, grid],
        modes: {
            default: ['drag-canvas', 'zoom-canvas'],
        },
        defaultNode: {
            // type: 'modelRect', //节点类型
            type: 'icon-node',
            size: [120, 40],
        },
        defaultEdge: {
            type: 'line',
            style: {
                stroke: '#999999',
            },
        },
        nodeStateStyles: {
            hover: {
                stroke: '#1890ff',
                lineWidth: 2,
            },
        },
        edgeStateStyles: {
            hover: {
                stroke: '#1890ff',
                lineWidth: 2,
            },
        },
        layout: defaultLayout,
    });
    // graph.fitView();
    graph.setMinZoom(0.5); //最小允许缩放比例
    graph.setMaxZoom(1.5); //最大允许缩放比例
    graph.data(data);
    graph.render();
    graph.fitCenter(); //（记住渲染后加入此方法）图将会被平移，图的中心将对齐到画布中心，但不缩放。优先级低于 fitView。

    /**
     * 树形图渲染完成
     */
    /**
     * 树形图节点操作
     * 
     *   svg自定义dom节点：  1. dom节点不能使用节点/边这些g6内置api,需要使用原生DOM事件（即行内事件，外部添加不生效）*   2.外部可以获取到元素信息，但是事件不能触发，这里用到事件委托可以解决
     *       $("div#addFu").click(function () {     //不生效
     *           console.log(11);
     *       })
     */
    $("svg").on("click", "#createModule", function (ev) {
        // console.log(data);
        $(".storyLineOpt").hide(200);
        let id = $(this).parent().parent().parent().find("section").attr("id");
        $(this).parent().parent().find("div.showOpt").hide(300);
        let info = graph.findDataById(id);
        // if (!info.children) {
        // }
        // console.log(info.children.length)
        if (info.children.length < 4) { //分支超过4个不可再创建
            const randNum = `n-${Math.random()}`;
            // 判断树叉的分支有几个，动态的在其前面加ABCD
            // if (info.children.length == 0) {
            //     info.children.push({
            //         id: randNum,
            //         label: "A: 拖拽素材至此",
            //         imgUrl: '',
            //         addFuUrl: "./images/hao.png",
            //     })
            // } else if (info.children.length == 1) {
            //     info.children.push({
            //         id: randNum,
            //         label: "B: 拖拽素材至此",
            //         imgUrl: '',
            //         addFuUrl: "./images/hao.png",
            //     })
            // } else if (info.children.length == 2) {
            //     info.children.push({
            //         id: randNum,
            //         label: "C: 拖拽素材至此",
            //         imgUrl: '',
            //         addFuUrl: "./images/hao.png",
            //     })
            // } else if (info.children.length == 3) {
            //     info.children.push({
            //         id: randNum,
            //         label: "D: 拖拽素材至此",
            //         imgUrl: '',
            //         addFuUrl: "./images/hao.png",
            //     })
            // }
            info.children.push({
                id: randNum,
                label: "拖拽素材至此",
                imgUrl: '',
                addFuUrl: "./images/hao.png",
            })
            info.noComponent = true; //  无组件且只有一个分支时，则自动播放下个视频
            graph.updateChild(info, id);
        }
        // graph.fitCenter(); // 创建新的分支后，svg宽度变大，然后再调用此方法，会再次居中
    }).on("click", "#delModule", function (ev) {
        $(".storyLineOpt").hide(200);
        let id = $(this).parent().parent().parent().find("section").attr("id");
        $(this).parent().parent().find("div.showOpt").hide(300);
        let info = graph.findDataById(id); //g6api  通过数据中某一个数据的id 过去数据本身
        info.children = []; //因为删除时，只删除分支，不能删除本身，g6树图没有提供此api，所以只能children为空数组然后重新渲染树图
        graph.updateChild(info, id);
        // graph.data(data);
        // graph.render();
        // graph.fitView();
    }).on("click", "section", function (ev) {
        $("svg").find("div.showOpt").hide(300); //点击某个树叉
        let id = $(this).attr("id");
        let info = graph.findDataById(id);
        console.log(info);
        /**
         * ai互动后不支持添加任何组件，只能ai互动播放完，自动播放下面的视频
         * @info.interGame._interId : 树杈数据结构里的互动素材id
         */
        if (info.interGame && info.interGame._interId) {
            $("#commitDialog").show(100).find("#commitAfterText").text("此树杈显示是AI互动素材，不支持在此树杈后设置组件");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
            return false;
        }
        /**
         *  //$(this).attr("playurl") 如果他为true时，则证明绑定了素材那就点击会在左上方加载素材内容，如果false则不需要加载
         */
        let isMaterial = $(this).attr("playurl");
        if (isMaterial) {
            // 素材库的内容点击，在右侧可以播放查看   判断比较麻烦要优化
            let houzhui = isMaterial.slice(isMaterial.lastIndexOf(".") + 1);
            if (houzhui == "png" || houzhui == "jpg" || houzhui == "jpeg" || houzhui == "gif" || houzhui == "webp") {
                $(".storeInfo").empty();
                $(".storeInfo").append(`<img src="${isMaterial}">`);
            } else if (houzhui == "mp4") {
                $(".storeInfo").empty();
                $(".storeInfo").append(`<video controls src="${isMaterial}"></video>`);
            } else if (houzhui == "mp3") {
                $(".storeInfo").empty();
                $(".storeInfo").append(`<audio src="${isMaterial}"></audio>`);
            }
        }
        /**
         * 点击树叉播放其绑定的素材
         */
        // 备课教案组件  TPmaterialId: '', //备课教案绑定得素材id  TPplayUrl: '', //绑定得素材播放地址TPimgUrl: "", //绑定得素材封面
        $("#tPFullDown img").attr("src", ""); //每次点击先重置教学素材
        let addFu = $(this).parent().parent().find("#addFu");
        let TPmaterialId = addFu.attr("TPmaterialId");
        if (TPmaterialId && TPmaterialId != "undefined") {
            let TPplayUrl = addFu.attr("TPplayUrl");
            let TPimgUrl = addFu.attr("TPimgUrl");
            let TPTip = addFu.attr('TPTip');
            $("#tPFullDown img").attr("src", TPimgUrl);
            $("#tPFullDown p").text(TPTip).attr({
                imgUrl: TPimgUrl,
                materialId: TPmaterialId,
                playUrl: TPplayUrl,
            });
            // $("#tPFullDown p").attr({
            //     imgUrl: TPimgUrl,
            //     materialId: TPmaterialId,
            //     playUrl: TPplayUrl,
            // });
        } else {
            $("#tPFullDown p").text("请选择素材");
        }
        /**
         * 备课教案组件结束
         */

        /**
         * 标注组件  如果有 -- 字段的话正在此分支有标注组件,那么其他组件无效
         */
        $(".setConLabel").remove();
        $(".setLabel").remove();
        $("#setLabelImg img").attr("src", "./images/blackGround.jpg")
        if (!info.children || info.children.length != 1) { //如果其后有多个多个组件，则不会回显数据
            console.log("标注不能生效");
        } else {
            let labelInfo = info.labelInfo;
            if (labelInfo) {
                $("#setLabelImg img").attr("src", labelInfo.labelBackgroundImg);
                for (let i = 0; i < labelInfo.num; i++) {
                    if (i == 0) {
                        zimu = "A";
                    } else if (i == 1) {
                        zimu = "B";
                    } else if (i == 2) {
                        zimu = "C";
                    } else if (i == 3) {
                        zimu = "D";
                    }
                    $("#setLabelInfo").append(`<div class="setConLabel">
                    <p>标注${zimu}</p>
                    <textarea maxlength="8">${labelInfo.textInfo[i]}</textarea>
                </div>`);
                    $("#setLabelImg").append(`
                    <div class="setLabel label${zimu}" style="left:${labelInfo.x[i]};top:${labelInfo.y[i]};transform:rotate(${labelInfo.rotate[i]}deg)">
                    <em class="iconfont icondian"></em>
                    <i></i>
                        <p>${labelInfo.textInfo[i]}</p>
                    </div>
                    `);
                }
            }
        }
        /**
         * 标注组件结束
         */
        // 画面暂停组件
        $("#switchBtn").attr("clickBool", 0).find("span").css({
            'border-color': '#dcdfe6',
            'background-color': '#dcdfe6'
        }).find("i").css({
            left: '2%',
            marginLeft: "0"
        });
        if (info.children) {
            if (info.pictureStop && info.pictureStop == 1 && info.children.length == 1) { //表示画面暂停组件在此分支上被应用
                $("#switchBtn").attr("clickBool", 1).find("span").css({
                    'border-color': 'rgba(51, 185, 248, 1)',
                    'background-color': 'rgba(51, 185, 248, 1)'
                }).find("i").css({
                    left: '100%',
                    marginLeft: "-44%"
                });
                $("#switchBtn")
            } else {
                $("#switchBtn").attr("clickBool", 0).find("span").css({
                    'border-color': '#dcdfe6',
                    'background-color': '#dcdfe6'
                }).find("i").css({
                    left: '2%',
                    marginLeft: "0"
                });
            }
        }
        // 画面暂停组件结束
        //根据分支确定选项卡的数量
        let defaultOption = info.defaultOption;
        if (info.children) {
            // let answerCon = item.answerName ? item.answerName : "输入选项名称...（24字符）"; //判断有没有更新过每个选项的标题，如果有标题则渲染标题到文本域，没有则请输入选项名称...（24字符）
            let infoCon = info.children;
            let infoLength = infoCon.length;
            $("#optionsInfo").empty();
            $("#SetSelImg p").remove();
            $.each(infoCon, function (index, item) {
                $("#SetSelImg").append(`<p class="options" id="sel${selABCD[index]}">${selABCD[index]}<span> ${item.answerName}<span></p>`)
                $("#optionsInfo").append(`
                <div id="${item.id}">
                <p>选项${selABCD[index]} 剧情模块：剧情名称</p>
                <textarea maxlength="24" bindEle='${selABCD[index]}'></textarea>
                </div><label><input type="radio" name="defaultSel" value="${item.id}">默认选项</label>
                `);
                // 点击渲染选项卡内容，有内容则渲染成value属性，无则渲染成playholder属性，
                // 用于应用时，判断每个选项卡是否都输入文本了。
                if (item.answerName) {
                    let ele = $("#optionsInfo textarea")[index];
                    $(ele).val(item.answerName);
                } else {
                    $("#optionsInfo textarea")[index].setAttribute("placeholder", "输入选项名称...（24字符）");;
                    let eleP = $("#SetSelImg .options>span")[index];
                    $(eleP).text("");
                }

                if (infoLength === 1) {
                    $("#selA").css({
                        left: "27.5%",
                        bottom: '4%'
                    })
                } else if (infoLength === 2) {
                    $("#selA").css({
                        bottom: '4%'
                    })
                    $("#selB").css({
                        bottom: '4%'
                    })
                } else if (infoLength === 3) {
                    $(".options").css({
                        width: "28%"
                    })
                    $("#selA").css({
                        left: "4%",
                        bottom: '4%'
                    })
                    $("#selB").css({
                        left: "36%",
                        bottom: '4%'
                    })
                    $("#selC").css({
                        left: "67%",
                        bottom: '4%'
                    })
                } else if (infoLength === 4) {
                    $("#selA").css({
                        left: "3%",
                        bottom: '22%'
                    })
                    $("#selB").css({
                        right: "3%",
                        bottom: '22%'
                    })
                    $("#selC").css({
                        left: "3%",
                        bottom: '4%'
                    })
                    $("#selD").css({
                        right: "3%",
                        bottom: '4%'
                    })
                }
            })
        } else {
            $("#optionsInfo").empty();
            $("#SetSelImg p").remove();
        }
        // 默认选项的单选按钮 ， 当数据结构中defaultOption与某一个单选框的value属性即树叉id相等时，默认选中。
        let daojishiInput = $("#daojishi");
        daojishiInput.removeAttr("checked"); //每次点击树叉弹出剧情设置时，都要把选项卡的双选设置为未选中
        let radios = $("#optionsInfo input[type=radio]");
        $.each(radios, function (i, item) {
            if ($(item).val() == defaultOption) {
                $(item).prop("checked", "checked");
                daojishiInput.prop("checked", "checked");
            }
        });
        radios.click(function () { //只要是这么单选被点击，那就证明现在是有一个默认选项的，所以双选框要被选中
            daojishiInput.prop("checked", "checked");
        })
        // 会叠加监听所以先解绑上一个 ~~~~ 为选项组件的倒计时双选矿加点击事件，当其未选中时，则所有单选框都不能有选中的。当其被选中时，默认选中第一个选项为默认选项。
        daojishiInput.unbind("click").click(function () {
            let bool = $(this).prop("checked");
            if (!bool) {
                radios.removeAttr("checked");
            } else {
                $(radios[0]).prop("checked", "checked");
            }
        })
        //根据分支确定选项卡的数量 结束--------
        // setLabelInfo 添加标注
        // $("#setLabelInfo div").siblings("div.setConLabel").remove()
        // setLabelInfo 添加标注结束--------
        let secText = $(this).children("span").text();
        /*   选项ABCD 回写
        let splitSel = secText.slice(secText.indexOf(": ") + 2);
        secText = splitSel
        */
        let secImg = $(this).attr("tip");
        if (!secImg || secImg == 'undefined') { //未绑定素材的树叉点出弹窗他的剧情模块设置时，回写到素材的input上会是undefined，所以加判断解决此bug
            $("#selMaterial").val("请选择"); //剧情选择的素材名称
        } else {
            $("#selMaterial").val(secImg); //剧情选择的素材名称
        }
        let playUrl = $(this).attr("playUrl"),
            materialid = $(this).attr("materialid"),
            secImgUrl = $(this).children("img").attr("src");
        $(".storyLineName").find("label").css("color", "#999");
        $("#juQName").val(secText);
        $("#selMaterial").attr({
            "imgUrl": secImgUrl, //剧情选择的素材
            "materialid": materialid, // 树叉绑定的素材 id （此id对应上传到阿里云服务器的id）
            "playUrl": playUrl //当点击预览互动视频时，直接调用这个地址
        })
        $("svg").find("section").css("border", "1px solid rgba(4, 0, 0, 0.14)");
        $(this).css("border", "2px solid #05A6F9");
        $(".storyLineOpt").attr("id", id).show(300);
        // 点击树叉 会给这个树叉添加右击事件 显示增删分支操作

    }).unbind("mouseenter").on("mouseenter", "#addFu", function (event) {
        // contextmenu 右击事件  section
        event.preventDefault();
        event.stopPropagation();
        $(".storyLineOpt").hide();
        let optTip = $(this).parent().parent();
        /**
         * 只能出现一个操作弹窗
         */
        $("svg").find(".showOpt").css("display", "none");
        optTip.find(".showOpt").show(300);
        /**
         * 
         */
        $("svg").find("section").css("border", "1px solid rgba(4, 0, 0, 0.14)")
        $(this).parent().parent().find("section").css("border", "2px solid #05A6F9"); //当移入加号时，左侧长方形边框换为  2px 蓝色
        let id = $(this).parent().parent().find("section").attr("id");
        let info = graph.findDataById(id); //g6api  通过数据中某一个数据的id 过去数据本身
        if (!info.children) {
            info.children = [];
        }
        if (info.children.length == 0) { //表示此时操作的节点是根节点，则不要显示删除节点的样式
            $(this).parent().parent().find("#delModule").css("display", "none");
        }
        // console.log(data)
        if (info.children.length >= 4) { //如果这个元素分支下已有4个子分支，咋不支持创建新的
            optTip.find("#createModule").css({
                cursor: "not-allowed",
            });
            optTip.find("#createModule").hover(function () {
                $(this).css("color", "#999"); //hover时效果
            }, function () {
                $(this).css({
                    cursor: "not-allowed",
                });
            });
        }
    });
    $("svg").contextmenu(function (e) {
        e.preventDefault();
    });
    // $(document).keypress(function (e) {
    //     // ctrl+z撤销
    //     if (e.ctrlKey && e.keyCode == 26) {
    //         console.log(revocation);
    //         graph.data(revocation);
    //         graph.render();
    //         graph.fitCenter();
    //     }
    // });
    /**
     * 树形图节点操作
     */
    if (typeof window !== 'undefined') {
        window.onresize = () => {
            if (!graph || graph.get('destroyed')) return;
            if (!container || !container.scrollWidth || !container.scrollHeight) return;
            graph.changeSize(container.scrollWidth, container.scrollHeight);
        };
    }
    /*树形图加载结束*/

    /*
    上传素材到阿里云服务器
    */
    function createUploader() {
        var uploader = new AliyunUpload.Vod({
            partSize: 1048576,
            parallel: 5,
            retryCount: 3,
            retryDuration: 2,
            userId: "1932293980427449",
            // 添加文件成功
            addFileSuccess: function (uploadInfo) {
                console.log("addFileSuccess: " + uploadInfo.file.name)
            },
            // 开始上传
            onUploadstarted: function (uploadInfo) {
                // console.log(uploadInfo)
                let file = uploadInfo.file;
                let data = {
                    token: userinfo.token,
                    type: file.type,
                    name: file.name,
                    title: userinfo.user_id + "/" + file.name,
                    size: file.size,
                    tag: "teachPlatform"
                }
                let isType = file.type.slice(0, file.type.indexOf("/")); //用来判断是video audio image 
                // console.log(isType)
                if (isType === 'image') {
                    $.ajax({
                        url: '' + testUrl + '/platform/upload/upload_image',
                        /*接口域名地址*/
                        type: 'post',
                        data: data,
                        headers: {
                            token: userinfo.token
                        },
                        success: function (res) {
                            let uploadAddress = res.data.UploadAddress
                            let uploadAuth = res.data.UploadAuth;
                            let videoId = res.data.ImageId;
                            uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
                        }
                    })
                } else if (isType === 'video') {
                    $.ajax({
                        url: '' + testUrl + '/platform/upload/upload_video',
                        /*接口域名地址*/
                        type: 'post',
                        data: data,
                        success: function (res) {
                            let uploadAddress = res.data.UploadAddress;
                            let videoId = res.data.VideoId;
                            let uploadAuth = res.data.UploadAuth;
                            uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
                        }
                    })
                }
            },
            // 文件上传成功
            onUploadSucceed: function (uploadInfo) {
                console.log(uploadInfo);
                let file = uploadInfo.file;
                let isType = file.type.slice(0, file.type.indexOf("/")); //用来判断是video audio image 
                if (isType === 'image') {
                    $(".conList ul li:last-child").find(".conBox").empty().append(`<img draggable="false" src=${aliyunUrl+uploadInfo.object} alt="">`);
                    SCArr.push({
                        fileName: file.name,
                        fileUrl: aliyunUrl + uploadInfo.object,
                        materialId: uploadInfo.videoId,
                        playUrl: aliyunUrl + uploadInfo.object,
                    });
                    // clickPreview('image'); // 点击在左侧预览
                } else if (isType === 'video') {
                    let coverImg = '';
                    /* 获取视频信息 */
                    let data = {
                        videoid: uploadInfo.videoId
                    }
                    let uploadFilesArr = $(".conList ul li");
                    setTimeout(() => { //解决上传视频到阿里云，阿里云生成视频信息有延迟
                        $.ajax({
                            url: `${testUrl}/platform/upload/get_video_info`,
                            /*接口域名地址*/
                            // data: JSON.stringify(data),
                            type: 'post',
                            data: data,
                            headers: {
                                token: userinfo.token
                            },
                            success: function (res) {
                                // console.log(res);
                                if (res.data.CoverURL) {
                                    coverImg = res.data.CoverURL;
                                    // 因为获取上传视频信息，需要延迟获取，所以导致对应的封面不能正确渲染最后一个li元素，所以加个判断
                                    $.each(uploadFilesArr, function (i, item) {
                                        let materialId = $(item).attr("materialId")
                                        if (materialId == uploadInfo.videoId) {
                                            $(item).find(".conBox").empty().append(`<img draggable="false" src="${coverImg}" alt="图片地址加载失败">`);
                                        }
                                    });
                                } else {
                                    coverImg = "./images/video.png"; //如果5秒后没有获取到视频信息，那就给其一个相对地址的图片
                                    $.each(uploadFilesArr, function (i, item) {
                                        let materialId = $(item).attr("materialId")
                                        if (materialId == uploadInfo.videoId) {
                                            $(item).find(".conBox").empty().append(`<img style="width:43%;height:70%;" draggable="false" src="${coverImg}" alt="图片地址加载失败">`);
                                        }
                                    });
                                }
                                SCArr.push({
                                    fileName: file.name,
                                    fileUrl: coverImg,
                                    materialId: uploadInfo.videoId,
                                    playUrl: aliyunUrl + uploadInfo.object
                                });
                            }
                        })
                    }, 5000);
                    /* 获取视频信息 */
                    // clickPreview('video'); // 点击在左侧预览
                } else if (isType === 'audio') {
                    $(".conList ul").append(`
                    <li class="dragStyle yinpin" isAudio="${aliyunUrl+uploadInfo.object}">
                        <div class="conBox">
                            <img draggable="false" src="./images/ruzhurenzheng.png" alt="">
                        </div>
                        <p>${file.name}</p>
                    </li>`);
                }
                dragMaterial();
            },
            // 文件上传失败
            onUploadFailed: function (uploadInfo, code, message) {
                console.log(uploadInfo);
                $("#commitDialog").show(100).find("#commitAfterText").text("文件上传失败");
                setTimeout(function () {
                    $("#commitDialog").hide(100);
                }, 1000)
            },
            // 取消文件上传
            onUploadCanceled: function (uploadInfo, code, message) {
                console.log(uploadInfo);
                $("#commitDialog").show(100).find("#commitAfterText").text("取消文件上传");
                setTimeout(function () {
                    $("#commitDialog").hide(100);
                }, 1000)
            },
            // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
            onUploadProgress: function (uploadInfo, totalSize, progress) {
                var progressPercent = Math.ceil(progress * 100);
                // console.log(uploadInfo);
                let file = uploadInfo.file;
                // console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + progressPercent + "%");
                let eleArr = '';
                if (progressPercent == "0") {
                    eleArr += `
                    <li class="dragStyle" playUrl="${aliyunUrl+uploadInfo.object}" materialId="${uploadInfo.videoId}" isImage="${aliyunUrl+uploadInfo.object}">
                        <div class="conBox">
                            ${progressPercent + "%"}
                        </div>
                        <p>${file.name}</p>
                    </li>`;
                }
                $(".conList ul").append(eleArr);
                $(".conList ul li:last-child").find(".conBox").text(progressPercent + "%");
            },
            // 上传凭证超时
            onUploadTokenExpired: function (uploadInfo) {
                // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                $('#status').text('文件上传超时!')
            },
            // 全部文件上传结束
            onUploadEnd: function (uploadInfo) {
                console.log("全部文件上传结束" + uploadInfo);
            }
        })
        return uploader
    }
    // 互动视频封面得图片上传  也是上传得阿里云
    function createUploaderCourseImg() {
        var uploader = new AliyunUpload.Vod({
            partSize: 1048576,
            parallel: 5,
            retryCount: 3,
            retryDuration: 2,
            userId: "1932293980427449",
            // 添加文件成功
            addFileSuccess: function (uploadInfo) {
                console.log("addFileSuccess: " + uploadInfo.file.name)
            },
            // 开始上传
            onUploadstarted: function (uploadInfo) {
                console.log(uploadInfo)
                let file = uploadInfo.file;
                let data = {
                    token: userinfo.token,
                    type: file.type,
                    name: file.name,
                    title: "封面",
                    size: file.size,
                    tag: "封面"
                }
                $.ajax({
                    url: '' + testUrl + '/platform/upload/upload_image',
                    /*接口域名地址*/
                    type: 'post',
                    data: data,
                    headers: {
                        token: userinfo.token
                    },
                    success: function (res) {
                        let uploadAddress = res.data.UploadAddress
                        let uploadAuth = res.data.UploadAuth;
                        let videoId = res.data.ImageId;
                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
                    }
                })
            },
            // 文件上传成功
            onUploadSucceed: function (uploadInfo) {
                console.log(uploadInfo);
                let file = uploadInfo.file;
                /**
                 * 封面图片上传成功 修改图片地址
                 */
                $(".cover label img").attr({
                    src: ""
                });
                $(".cover label img").attr({
                    src: aliyunUrl + uploadInfo.object,
                    width: '100%',
                    height: "100%"
                });
                $(".cover label").attr({
                    background: "#F2FBFF"
                });
                $("#uploadFileOpt").css("opacity", "1");
            },
            // 文件上传失败
            onUploadFailed: function (uploadInfo, code, message) {
                console.log(uploadInfo);
                alert("文件上传失败");
            },
            // 取消文件上传
            onUploadCanceled: function (uploadInfo, code, message) {
                console.log(uploadInfo);
                alert("取消文件上传");
            },
            // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
            onUploadProgress: function (uploadInfo, totalSize, progress) {
                console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
                var progressPercent = Math.ceil(progress * 100);
            },
            // 全部文件上传结束
            onUploadEnd: function (uploadInfo) {
                $('#status').text('!文件上传完毕');
            }
        })
        return uploader
    }
    // 互动视频封面得图片上传  也是上传得阿里云
    function UploaderLabelBack() {
        var uploader = new AliyunUpload.Vod({
            partSize: 1048576,
            parallel: 5,
            retryCount: 3,
            retryDuration: 2,
            userId: "1932293980427449",
            // 添加文件成功
            addFileSuccess: function (uploadInfo) {
                console.log("addFileSuccess: " + uploadInfo.file.name)
            },
            // 开始上传
            onUploadstarted: function (uploadInfo) {
                console.log(uploadInfo)
                let file = uploadInfo.file;
                let data = {
                    token: userinfo.token,
                    type: file.type,
                    name: file.name,
                    title: "封面",
                    size: file.size,
                    tag: "封面"
                }
                $.ajax({
                    url: '' + testUrl + '/platform/upload/upload_image',
                    /*接口域名地址*/
                    type: 'post',
                    data: data,
                    headers: {
                        token: userinfo.token
                    },
                    success: function (res) {
                        let uploadAddress = res.data.UploadAddress
                        let uploadAuth = res.data.UploadAuth;
                        let videoId = res.data.ImageId;
                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
                    }
                })
            },
            // 文件上传成功
            onUploadSucceed: function (uploadInfo) {
                console.log(uploadInfo);
                let file = uploadInfo.file;
                /**
                 * 封面图片上传成功 修改图片地址
                 */
                $("#setLabelImg img").attr({
                    src: aliyunUrl + uploadInfo.object
                });
                // labelInfo.labelBackgroundImg=aliyunUrl + uploadInfo.object;
                $("#userTip").text("更换背景图")
            },
            // 文件上传失败
            onUploadFailed: function (uploadInfo, code, message) {
                console.log(uploadInfo);
                alert("文件上传失败");
            },
            // 取消文件上传
            onUploadCanceled: function (uploadInfo, code, message) {
                console.log(uploadInfo);
                alert("取消文件上传");
            },
            // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
            onUploadProgress: function (uploadInfo, totalSize, progress) {
                console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
                var progressPercent = Math.ceil(progress * 100);
            },
            // 全部文件上传结束
            onUploadEnd: function (uploadInfo) {
                $('#status').text('!文件上传完毕');
            }
        })
        return uploader
    }
    var uploader = null;
    $('#uploadImg').on('change', function (e) {
        // 上传素材图片
        var file = e.target.files;
        console.log(file);
        if (!file) {
            alert("请先选择需要上传的文件!");
            return;
        }
        var userData = '{"Vod":{}}'
        uploader = createUploader()
        for (let i = 0; i < file.length; i++) { //添加多个视频得方法
            // console.log(file[i])
            uploader.addFile(file[i], null, null, null, userData);
        }
        uploader.startUpload();
    });
    $('#uploadVideo').on('change', function (e) {
        // 上传素材视频
        var file = e.target.files;
        console.log(file);
        if (!file) {
            alert("请先选择需要上传的文件!");
            return;
        }
        var userData = '{"Vod":{}}'
        uploader = createUploader()
        for (let i = 0; i < file.length; i++) { //添加多个视频得方法
            // console.log(file[i])
            uploader.addFile(file[i], null, null, null, userData);
        }
        uploader.startUpload();
    });
    $('#uploadImgs').on('change', function (e) { //课程封面
        // 课程封面上传图片
        var file = e.target.files[0];
        if (!file) {
            alert("请先选择需要上传的文件!");
            return;
        }

        var userData = '{"Vod":{}}'
        uploader = createUploaderCourseImg()
        uploader.addFile(file, null, null, null, userData);
        uploader.startUpload();
    });
    $('#uploadLabelBack').on('change', function (e) { //标注组件背景图
        // 课程封面上传图片
        var file = e.target.files[0];
        if (!file) {
            alert("请先选择需要上传的文件!");
            return;
        }
        var userData = '{"Vod":{}}'
        uploader = UploaderLabelBack()
        uploader.addFile(file, null, null, null, userData);
        uploader.startUpload();
    });
    /*
        上传素材到阿里云服务器结束
    */
    // 添加类型按钮
    $("#addUpload").unbind("click").click(function () {
        $(".storyLineOpt").hide(300); //当添加出来得时候隐藏剧情操作
        $(".upload").toggle(300);
    })
    // 选项卡设置 点击出来操作栏
    $("#selTabBox h5").unbind("click").click(function () {
        // 剧情模块设置
        $(this).siblings(".pullDown").slideToggle(300);
    })
    $("#labelBox h5").unbind("click").click(function () {
        // 选项卡设置
        $(this).siblings(".pullDown").slideToggle(300);
    })
    $("#mulViewBox h5").unbind("click").click(function () {
        // 多视角设置
        alert("正在更新");
        return false;
        $(this).siblings(".pullDown").slideToggle(300);
    })
    $("#teachPlan h5").unbind("click").click(function () {
        // 标注设置  备课教案
        $(this).siblings(".pullDown").slideToggle(300);
    })
    // #cancelAllmodi 剧情操作模块 取消按钮
    $("#cancelAllmodi").unbind("click").click(function () {
        $(".storyLineOpt").hide(300);
    })
    // 剧情模板上面的素材选择下拉框，当用户输入信息时，提示他要选择下拉中的内容
    $("#selMaterial").change(function (e) {
        e.preventDefault();
        $(this).val("请在下拉框中选择素材");
        $(this).parent().css("color", "red");
    });

    // 关闭按钮
    $(".close").unbind("click").click(function (e) {
        $(this).parent().parent().slideUp(200);
        // 当关闭互动视频预览弹窗对应将视频暂停
        $("#preVideo").trigger('pause');
        $("#teachVideo").trigger('pause');
    });

    //storyLineOpt
    // $(".storyLineOpt").scroll(function () {
    //     console.log(11);
    //     let scrollTop = $(this).scrollTop();
    //     let header = $("#storyLineOptHead");
    //     let headerHeight = header.height();
    // });
    // 课件名称与封面设置    确定按钮
    // $("#confirm").click(function (e) {
    //     e.preventDefault();
    //     let courseN = $("#courseName").val();
    //     let imgUrl = $(".cover label img").attr("src");
    //     if (courseN && imgUrl != "./images/courseImgUpload.png") {
    //         courseImgUrl = imgUrl;
    //         courseName = courseN;
    //         // console.log(courseImgUrl, courseName);
    //     }
    // });
    /**
     * 剧情模块设置 --------------------------------------------------------------------------------
     */
    // 剧情模块设置右上角应用按钮
    $("#setAllmodi").unbind("click").click(function (ev) {
        let id = $(this).parent().parent().parent().attr("id");
        let info = graph.findDataById(id);
        console.log(info);
        if (info.interGame) {
            // ai互动的树杈是打不开模块设置的，所以应用的时候直接删除树杈数据结构里的interGame字段
            delete info.interGame;
        }
        /**
         * 备注组件
         */
        let labelLength = $("#setLabelInfo .setConLabel").length;
        let labelHasText = false;
        if (labelLength > 0) {
            if (!info.children || info.children.length != 1) { //此分支后只有一个分支时，才会ok
                $("#commitDialog").show(100).find("#commitAfterText").text("标注组件后只能有一个组件");
                setTimeout(function () {
                    $("#commitDialog").hide(100);
                }, 1000)
                return false;
            }
            $.each($(".setConLabel textarea"), function (i, item) {
                if (!$(item).val()) {
                    labelHasText = false;
                    return false;
                } else {
                    labelHasText = true;
                    if (i == 0) {
                        labelInfo.textInfo[0] = $(item).val();
                        labelInfo.num = 1;
                    } else if (i == 1) {
                        labelInfo.textInfo[1] = $(item).val();
                        labelInfo.num = 2;
                    } else if (i == 2) {
                        labelInfo.num = 3;
                        labelInfo.textInfo[2] = $(item).val();
                    } else if (i == 3) {
                        labelInfo.textInfo[3] = $(item).val();
                        labelInfo.num = 4;
                    };
                }
            });
            info.labelInfo = JSON.parse(JSON.stringify(labelInfo)); //深拷贝每一个labelInfo要保证存储地址是不一样
            info.labelInfo.labelBackgroundImg = $("#setLabelImg img").attr("src");
        } else {
            delete info.labelInfo;
            labelHasText = true;
        }
        if (!labelHasText) {
            $("#commitDialog").show(100).find("#commitAfterText").text("标注不能为空");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
            return false;
        }
        // console.log(info);
        /**
         * 备注组件结束
         */

        /**
         * // 先判断备课教案组件是否被应用
                //     TPmaterialId:'',  //备课教案绑定得素材id
                //     TPplayUrl:'',     //绑定得素材播放地址
                //     TPimgUrl:"",     //绑定得素材封面
         */
        let TPmaterialId = $("#teachPlan p").attr("materialId");
        if (TPmaterialId) {
            let TPplayUrl = $("#teachPlan p").attr("playurl"),
                TPTip = $("#teachPlan p").text(),
                TPimgUrl = $("#teachPlan p").attr("imgurl");
            info.TPmaterialId = TPmaterialId;
            info.TPplayUrl = TPplayUrl;
            info.TPimgUrl = TPimgUrl;
            info.TPTip = TPTip;
            info.addFuUrl = "./images/beikeicon.png"
        } else if (TPmaterialId == '') { //选择无素材时,证明不用此组件
            info.TPmaterialId = '';
            info.TPplayUrl = '';
            info.TPimgUrl = '';
            info.TPTip = '';
            info.addFuUrl = "./images/hao.png"
        } else {
            info.addFuUrl = "./images/hao.png"
        }
        /**
         *先判断画面暂停组件是否被应用，如果被应用要判断此分支后是否是单独分支，如果是单独分支则可以应用，如果是多分支**则不可以应用。
         */
        let switchBtn = $("#switchBtn")
        let switchBtnbool = parseInt(switchBtn.attr("clickBool"));
        if (switchBtnbool) {
            // console.log(switchBtnbool); //1  证明启动了此组件
            // console.log(info);
            if (info.children) {
                if (!(info.children.length == 1)) {
                    switchBtnbool = 0;
                    switchBtn.attr("clickBool", switchBtnbool).find("span").css({
                        'border-color': '#dcdfe6',
                        'background-color': '#dcdfe6'
                    }).find("i").css({
                        left: '2%',
                        marginLeft: "0"
                    });
                    $("#commitDialog").show(100).find("#commitAfterText").text("此阶段后只有一个分支时，才可使用");
                    setTimeout(function () {
                        $("#commitDialog").hide(100);
                    }, 1000)
                    return false;
                }
            }
        }
        info.pictureStop = switchBtnbool;
        // 判断画面暂停组件完成。
        // 空字符串为false
        let bool = false;
        let juQName = $("#juQName").val(); //剧情名
        // console.log(info.label.indexOf(": ") );

        /**
         *   let sliceinfolabel = ""; //如果查找到 :  则证明前面有ABCD  如果没有找到则不执行
         *   info.label.indexOf(": ") == 1 ? sliceinfolabel = info.label.slice(0, info.label.indexOf(": ") + *   2) : sliceinfolabel = "";
         *   let sliceinfolabel = info.label.slice(0, info.label.indexOf(": ") + 2); //应用后，是每个分支的*     label都有对应的选项提示用户，此分支为选项几。
         */
        let SCName = $("#selMaterial").val(), //素材名称
            juQMain = $("#selMaterial").attr("imgUrl"), //剧情选择的素材
            materialId = $("#selMaterial").attr("materialId"),
            playUrl = $("#selMaterial").attr("playUrl");
        if (!playUrl) { // 
            $("#commitDialog").show(100).find("#commitAfterText").text("请选择素材");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
            return false;
        }
        //  判断剧情模块选项卡的文本域每个是否都有内容，无内容不允许提交
        let textareaSum = $("#optionsInfo textarea");
        // 当文本框只有一个时，表示只有一个分支，一个分支时不需要在去判断其是否必须选择选项卡内容
        if (textareaSum.length != 1) {
            $.each(textareaSum, function (i, item) {
                if (!$(this).val()) {
                    bool = false;
                } else {
                    bool = true
                }
            });
            if (!bool && textareaSum.length != 0) {
                $("#commitDialog").show(100).find("#commitAfterText").text("选项卡内容未填写");
                setTimeout(function () {
                    $("#commitDialog").hide(100);
                }, 1000)
                return false;
            }
        }
        /*
         * 倒计时双选是否被选中
         */
        let countDown = $(".countDown input").prop("checked");
        let radios = $("#optionsInfo input[type=radio]");
        if (countDown) {
            $.each(textareaSum, function (i, item) {
                if (!$(this).val()) {
                    bool = false;
                } else {
                    bool = true
                }
            });
            if (!bool) {
                $("#commitDialog").show(100).find("#commitAfterText").text("选项卡内容未填写");
                setTimeout(function () {
                    $("#commitDialog").hide(100);
                }, 1000)
                return false;
            }
            $.each(radios, function (i, item) {
                if ($(item).prop("checked")) {
                    info.defaultOption = $(item).val();
                }
            });
        } else {
            info.defaultOption = '';
        }
        /*
         * 倒计时双选是否被选中完成
         */
        /**
         * 无组件且只有一个分支时，则自动播放下个视频
         */
        // console.log(info.defaultOption, !info.defaultOption);
        // console.log(info.pictureStop, !info.pictureStop);
        // console.log(bool, !bool);
        console.log(!info.labelInfo);
        if (!info.defaultOption && !info.pictureStop && !bool && !info.labelInfo) {
            console.log("无组件且只有一个分支时，则自动播放下个视频");
            info.noComponent = true;
        } else {
            info.noComponent = false;
        }
        /**
         * 无组件且只有一个分支时，则自动播放下个视频  ------结束
         */
        /**
         * 对数据结构进行赋值
         */
        // info.label = sliceinfolabel + juQName; //A：+ 剧情名 / B：剧情名 。。。。。。
        info.label = juQName; //A：+ 剧情名 / B：剧情名 。。。。。。
        info.imgUrl = juQMain;
        info.tip = SCName;
        info.materialId = materialId;
        info.playUrl = playUrl;
        // console.log(switchBtnbool);
        let selSum = $("#optionsInfo div");
        $.each(selSum, function (i, item) {
            let ele = $(this).find("textarea");
            // let bindele = ele.attr("bindele");
            let eleText = ele.val();
            info.children[i].answerName = eleText;
            // console.log(info.children[i].answerName);
        });
        // graph.data(data);
        graph.updateChild(info, id);
        graph.render();
        graph.fitView();
        // console.log($("svg>g").attr("transform", "matrix(1,0,0,1,300.99999809265137,277.5)"));
        /**
         * 对数据结构进行赋值
         */
        $(".storyLineOpt").hide(200);
    });
    // 素材选择栏
    $("#selMaterial").unbind("click").click(function (e) {
        let listBox = $("#showMaterial");
        if (SCArr.length !== $("#showMaterial li").length) {
            listBox.empty();
            let eleArr = '';
            $.each(SCArr, function (index, item) {
                eleArr += `<li playUrl="${item.playUrl}" materialId="${item.materialId}" imgUrl="${item.fileUrl}">${item.fileName}</li>`
            });
            listBox.append(eleArr);
        }
        listBox.toggle(200);
        //剧情模块设置素材选择下拉框
        $(".storyLineName li").unbind("click").click(function () {
            let materialId = $(this).attr("materialId"),
                playUrl = $(this).attr("playUrl"),
                clickText = $(this).text(),
                imgUrl = $(this).attr("imgUrl");
            if (!imgUrl) { //如果封面地址为空，则给他加默认视频封面
                imgUrl = "./images/video.png"
            }
            $(this).addClass("active").siblings().removeClass("active");
            $("#selMaterial").val(clickText).attr({
                imgUrl,
                materialId,
                playUrl
            });;
            $("#juQName").val(clickText);
            $(".storyLineName").find("label").css("color", "#999");
            listBox.hide(200);
        });
        $(".storyLineName").unbind().mouseleave(function (e) {
            e.preventDefault();
            e.stopPropagation();
            listBox.hide(200);
        })
    });
    /* #SetSelImg  选项卡点击出弹窗 */
    $("#SetSelImg").unbind("click").click(function (e) {
        $("#selCardDiagBox").show(200);
        let cloneEle = $(this).clone().attr("class", "selCardDiag");
        $("#selCardDiagBox .centerBox .selCardDiag").remove();
        $("#selCardDiagBox .centerBox").append(cloneEle);
    });
    // 备课教案下拉
    $("#tPFullDown p").unbind("click").click(function (e) {
        if (SCArr.length + 1 !== $("#tPFullDown ul li").length) {
            $("#tPFullDown ul li#noneSC").siblings().remove();
            $.each(SCArr, function (index, item) {
                $("#tPFullDown ul").append(`<li playUrl="${item.playUrl}" materialId="${item.materialId}" imgUrl="${item.fileUrl}">${item.fileName}</li>`);
            });
        }
        $("#tPFullDown ul").toggle(200);
        //剧情模块设置素材选择下拉框
        $("#tPFullDown li").unbind("click").click(function () {
            let cliIndex = $(this).index();
            if (cliIndex === 0) {
                $("#tPFullDown ul").hide(200);
                $("#tPFullDown p").text("无素材");
                $("#tPFullDown img").attr("src", "");
                $(this).addClass("active").siblings().removeClass("active");
                $("#tPFullDown p").attr({
                    imgUrl: "",
                    materialId: "",
                    playUrl: ""
                });
                return false;
            }
            let materialId = $(this).attr("materialId");
            let playUrl = $(this).attr("playUrl");
            let clickText = $(this).text();
            let imgUrl = $(this).attr("imgUrl");
            $(this).addClass("active").siblings().removeClass("active");
            $("#tPFullDown p").text(clickText);
            $("#tPFullDown img").attr("src", imgUrl);
            $("#tPFullDown p").attr({
                imgUrl,
                materialId,
                playUrl
            });
            $("#tPFullDown ul").hide(200);
        });
        $("#tPFullDown ul").unbind().mouseleave(function (e) {
            e.preventDefault();
            e.stopPropagation();
            $("#tPFullDown ul").hide(200);
        })
    });
    /**   标注组件   */
    $("#createLabel").unbind("click").click(function () { //createLabel 剧情模块设置中的标注模块
        let num = $(".setConLabel").length;
        let zimu = "A";
        if (num == 0) {
            zimu = "A";
        } else if (num == 1) {
            zimu = "B";
        } else if (num == 2) {
            zimu = "C";
        } else if (num == 3) {
            zimu = "D";
        }
        if (num >= 4) {
            $(this).css({
                cursor: "not-allowed"
            })
            return false;
        }
        $("#setLabelInfo").append(`<div class="setConLabel">
        <p>标注${zimu}</p>
        <textarea maxlength="8" placeholder="请输入标注内容（8字符）"></textarea>
    </div>`);
        $("#setLabelImg").append(`
        <div class="setLabel label${zimu}">
        <em class="iconfont icondian"></em>
        <i></i>
        <p>请输入标注${zimu}</p>
    </div>
    `)
    });
    $("#setLabelInfo").unbind("input").on("input", "textarea", function () {
        // console.log($(this).parent().index()); // 1 2 3 4
        let ind = $(this).parent().index();
        if (ind == 1) {
            $(".labelA p").text($(this).val());
        } else if (ind == 2) {
            $(".labelB p").text($(this).val());
        } else if (ind == 3) {
            $(".labelC p").text($(this).val());
        } else if (ind == 4) {
            $(".labelD p").text($(this).val());
        }
    });
    $("#setLabelImg").click(function (e) { // 点击预览标注组件
        e.preventDefault();
        let cloneEle = $("#setLabelImg").clone().attr("id", "PreSetLabelImg");
        $("#labelDiagPreBox").show(200);
        $("#PreSetLabelImg").remove();
        $("#labelDiagPreBox .centerBox").append(cloneEle);
    });

    var labelInfo = { //标注信息
        labelBackgroundImg: "./images/blackGround.jpg", //背景图片
        x: ["10%", "50%", "10%", "55%"],
        y: ["80%", "80%", "30%", "30%"],
        textInfo: ["", "", "", ""],
        rotate: ["0", "0", "0", "0"]
    }
    $("#labelDiagPreBox .centerBox").on('mousedown', '.setLabel', function (event) {
        event.preventDefault();
        event.stopPropagation();
        $(this).attr("id", "on");
        let ind = $(this).index(); //从 1开始
        let that = this;
        /**
         * 被点击的元素距离页面可视左上角
         */
        X = event.pageX;
        Y = event.pageY;
        /**
         * 被点击的元素距离页面可视左上角
         */
        /**
         * 被点击的元素定位距离
         */
        let left = $(this).position().left;
        let top = $(this).position().top;
        /**
         * 被点击的元素定位距离
         */
        /**
         * 定位元素的父级的宽高，不包含margin   width(是元素的实际宽高)
         */
        let wid = $("#PreSetLabelImg").outerWidth();
        let hei = $("#PreSetLabelImg").outerHeight();
        let sonWidth = $(this).outerWidth();
        let sonHeight = $(this).outerHeight();
        /**
         * 定位元素的父级的宽高，不包含margin   width(是元素的实际宽高)
         */
        $(this).css({
            left: parseInt(left),
            top: parseInt(top),
        })
        $(document).mousemove(function (e1) {
            e1.preventDefault();
            e1.stopPropagation();
            // e1.pageX   是被移动元素距离页面可视左上角
            // e1.pageX - X  是移动元素距离左上角的距离 - 被点击元素（即是移动元素）点击的那一刻距离左上角的距离  就是每次移动过的距离
            moveX = left + e1.pageX - X;
            moveY = top + e1.pageY - Y;
            let labelOffX = parseInt(moveX / wid * 100);
            let labelOffY = parseInt(moveY / hei * 100);
            if (moveX < 0) {
                $(that).css({
                    left: 0 + "%",
                    top: labelOffY + '%',
                })
            } else
            if (moveX > (wid - sonWidth)) {
                $(that).css({
                    left: parseInt((wid - sonWidth) / wid * 100) + "%",
                    top: labelOffY + '%',
                })
            } else
            if (moveY < 0) {
                $(that).css({
                    top: 0 + '%',
                    left: labelOffX + "%",
                })
            } else
            if (moveY > (hei - sonHeight)) {
                $(that).css({
                    top: parseInt((hei - sonHeight) / hei * 100) + "%",
                    left: labelOffX + "%",
                })
            } else {
                $(that).css({
                    left: labelOffX + "%",
                    top: labelOffY + '%',
                })
            }

            if (ind == 1) {
                $("#setLabelImg .labelA").css({
                    left: labelOffX + "%",
                    top: labelOffY + '%',
                })
                labelInfo.x[0] = labelOffX + "%";
                labelInfo.y[0] = labelOffY + "%";
            } else if (ind == 2) {
                $("#setLabelImg .labelB").css({
                    left: labelOffX + "%",
                    top: labelOffY + '%',
                })
                labelInfo.x[1] = labelOffX + "%";
                labelInfo.y[1] = labelOffY + "%";
            } else if (ind == 3) {
                $("#setLabelImg .labelC").css({
                    left: labelOffX + "%",
                    top: labelOffY + '%',
                })
                labelInfo.x[2] = labelOffX + "%";
                labelInfo.y[2] = labelOffY + "%";
            } else {
                $("#setLabelImg .labelD").css({
                    left: labelOffX + "%",
                    top: labelOffY + '%',
                })
                labelInfo.x[3] = labelOffX + "%";
                labelInfo.y[3] = labelOffY + "%";
            }
        }).mouseup(function (e2) {
            e2.preventDefault();
            e2.stopPropagation();
            $(document).unbind();
            $(that).attr("id", "");
        })
        // .unbind("mouseleave").mouseleave(function () {
        //     $("#PreSetLabelImg").unbind();
        // })
    }).unbind("mouseenter").on('mouseenter', 'em', function (e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass("icondian").css("color", "blue").addClass("iconxuanzhuan1");
        $(this).unbind("click").click(function () {
            // console.log("点击旋转");
            let ind = $(this).parent().index();
            let eleDeg = getEleRotate($(this).parent()[0]);
            // console.log(eleDeg);
            if (eleDeg >= 360) {
                eleDeg = 0
            }
            eleDeg += 90;
            $(this).parents(".setLabel").css({
                "transform": "rotate(" + eleDeg + "deg)"
            })
            if (ind == 1) {
                $("#setLabelImg .labelA").css({
                    "transform": "rotate(" + eleDeg + "deg)"
                })
                labelInfo.rotate[0] = eleDeg;
            } else if (ind == 2) {
                $("#setLabelImg .labelB").css({
                    "transform": "rotate(" + eleDeg + "deg)"
                })
                labelInfo.rotate[1] = eleDeg;
            } else if (ind == 3) {
                $("#setLabelImg .labelC").css({
                    "transform": "rotate(" + eleDeg + "deg)"
                })
                labelInfo.rotate[2] = eleDeg;
            } else {
                $("#setLabelImg .labelD").css({
                    "transform": "rotate(" + eleDeg + "deg)"
                })
                labelInfo.rotate[3] = eleDeg;
            }
        })
    }).unbind("mouseleave").on('mouseleave', 'em', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        $(this).removeClass("iconxuanzhuan1").css("color", "#666").addClass("icondian")
    });

    function getEleRotate(el) { //获取css3transform中的旋转角度
        // var el = document.getElementById("divTransform");
        var st = window.getComputedStyle(el, null);
        var tr = st.getPropertyValue("-webkit-transform") ||
            st.getPropertyValue("-moz-transform") ||
            st.getPropertyValue("-ms-transform") ||
            st.getPropertyValue("-o-transform") ||
            st.getPropertyValue("transform") ||
            "FAIL";
        // With rotate(30deg)...
        // matrix(0.866025, 0.5, -0.5, 0.866025, 0px, 0px)
        // console.log('Matrix: ' + tr);
        // rotation matrix - http://en.wikipedia.org/wiki/Rotation_matrix
        var values = tr.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var c = values[2];
        var d = values[3];
        var scale = Math.sqrt(a * a + b * b);
        // console.log('Scale: ' + scale);
        // arc sin, convert from radians to degrees, round
        var sin = b / scale;
        // next line works for 30deg but not 130deg (returns 50);
        // var angle = Math.round(Math.asin(sin) * (180/Math.PI));
        var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
        // console.log('Rotate: ' + angle + 'deg');
        return angle;
    }
    // var deg = 0;
    /**   标注组件完成   */
    // 课件名称正则验证
    $("#courseName").unbind().bind("input", function (e) {
        let regu = "^[a-zA-Z0-9\u4e00-\u9fa5]+$";
        var re = new RegExp(regu);
        if ($(this).val().search(re) != -1) { //;不等于-1证明正确
            $("#interactCouName>p").hide();
        } else {
            $("#interactCouName>p").show().text("只能输入中文英文数字");
        }
    });
    // 如果回写的互动视频status为0（1.发布会直接将status改为1  2.报存会覆盖之前的）  status为1（1.发布会直接覆盖  2.保存会创建一个新的status为0并且id不同的互动视频） 
    //发布互动视频按钮 到机构
    $("#publish").click(function (e) {
        e.preventDefault();
        let courseN = $("#courseName").val(),
            imgUrl = $(".cover label img").attr("src"),
            isPublishBool = true;
            regu = "^[a-zA-Z0-9\u4e00-\u9fa5]+$", // 课件名称正则验证
            re = new RegExp(regu);
        if ($("#courseName").val().search(re) != -1) { //不等于-1证明正确
            $("#interactCouName>p").hide();
        } else {
            $("#commitDialog").show(100).find("#commitAfterText").text("课件名称错误");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
            $("#interactCouName>p").show().text("只能输入中文英文数字");
            return false;
        }
        // 课件名称正则验证结束

        if (courseN && imgUrl != "./images/courseImgUpload.png") {
            courseImgUrl = imgUrl;
            courseName = courseN;
            console.log(courseName, courseImgUrl);
            // ---------------------------------------------------------------- 有问题 isPublishBool 
            // if (hrefInfo) { //判断是否是重复发布
            //     isPublishBool = confirm("此发布会覆盖之前发布的课件");
            // } //重复发布并且选择确认则执行后面，如果取消则不执行
            // // console.log(isPublishBool);
            // if (!isPublishBool) {
            //     return false;
            // }
            // *****************************************
            data.SCArr = SCArr;
            let reqData = {
                id: hrefInfo,
                title: courseName,
                cover: courseImgUrl,
                type: "6", //1 视频 2 图片 3 音频 4 图片目录 5 文字 6 动态课件
                is_screen: "1",
                context: JSON.stringify(data),
                status: 2 //表示互动课件已完成， 并且发布到机构（需要机构审核）
            };
            $.ajax({
                type: "post",
                url: `${testUrl}/S9vC7rYOo4.php/small/resource/add`,
                // url: `${testUrl}/platform/resource/save`,
                headers: {
                    token: userinfo.token
                },
                data: reqData,
                success: function (res) {
                    console.log(res);
                    alert(res.msg)
                }
            });
        } else {
            $("#commitDialog").show(100).find("#commitAfterText").text("请先上传课件名称与封面");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
        }
        // ----------------------------------------------------------------
    });
    /**
     * 剧情模块设置 --------------------------------------------------------------------------------
     */
    /**
     * 素材拖动实际是创建一个新元素进行拖动，将新元素定位到鼠标的位置
     */
    function dragMaterial() {
        // ：jQuery中的click事件会累计绑定（导致会多次触发造成卡顿）所以我们可以在下次点击前先解绑jq绑定事件
        /**  当分支增多时会造成卡顿 
         *   graph.data(data);
                    graph.render();
                    graph.fitView();
         */
        $("#materialStore li.dragStyle").unbind().bind("mousedown", function (event) {
            // if ($(this).attr("_interId")) {
            //     return false
            // }
            console.group("普通素材拖拽参数")
            event.preventDefault();
            let moveEle = $(this).clone().attr("id", "rootEle"); //rootEle id 是为了给克隆的移动元素加一些样式
            $("body").append(moveEle);
            let distanceCliX = event.clientX;
            let distanceCliY = event.clientY;
            let mouseEnterTimer = null;
            $("body>.dragStyle").css({
                left: distanceCliX - 50 + "px",
                top: distanceCliY - 30 + "px"
            });
            let id = "",
                materialId = $(this).attr("materialId"),
                playUrl = $(this).attr("playUrl"),
                textCon = $(this).find("p").text(),
                imgUrlInfo = $(this).find("img").attr("src");
            // console.log("长按中");
            $("body").unbind("mousemove").mousemove(function (e) {
                e.stopPropagation();
                var offX = e.clientX;
                var offY = e.clientY;
                $("body>.dragStyle").css({
                    left: offX - 50,
                    top: offY - 10
                })
                $("svg section").mouseenter(function (e2) { //移动到某一个树叉的元素范围内，获取这个树叉的id字段
                    e2.stopPropagation();
                    mouseEnterTimer = setTimeout(() => { //只有拖到树叉上并且停留了500ms后才会成功
                        id = $(this).attr("id");
                        that = this;
                    }, 300);
                });
            }).unbind("mouseup").mouseup(function (e1) {
                e1.stopPropagation();
                clearTimeout("mouseEnterTimer");
                if (id) {
                    let info = graph.findDataById(id);
                    console.log(info);
                    if (info.interGame) {
                        delete info.interGame
                    }
                    console.log(info);
                    info.label = textCon;
                    info.imgUrl = imgUrlInfo;
                    info.tip = textCon;
                    info.materialId = materialId;
                    info.playUrl = playUrl;
                    // graph.data(data);
                    graph.updateChild(info, id);
                    graph.render();
                    graph.fitView();
                }
                $(".storyLineOpt").hide();
                console.log("清除");
                $("body").unbind();
                $("body>.dragStyle").remove();
                console.groupEnd("普通素材拖拽参数")
            });
        });
    }
    $("#optionsInfo").unbind("input").on("input", "textarea", function () {
        let bindEleId = $(this).attr("bindEle");
        let textCon = $(this).val();
        if (bindEleId === "A") {
            $("#selA span").text(textCon);
        } else if (bindEleId === "B") {
            $("#selB span").text(textCon);
        } else if (bindEleId === "C") {
            $("#selC span").text(textCon);
        } else if (bindEleId === "D") {
            $("#selD span").text(textCon);
        }
    });

    /**   视频播放
     *   @viewVideo    预览互动视频按钮id
     *   @preVideo     播放互动视频的video id
     *   @teachVideo   教学视频的video id
     */
    // 禁止预览的video右击事件
    $("#preVideo").contextmenu(function (e) {
        e.preventDefault();
    })
    // 预览互动视频的按钮
    $("#viewVideo").click(function (e) {
        e.preventDefault();
        console.group("预览视频播放器的逻辑")
        console.log(data);
        let children = data.children;
        let preVideo = $("#preVideo"); //视频video
        var interGame = "";
        if (data.interGame) {
            console.log("跟树杈是ai互动");
            interGame = data.interGame;
        } else {
            $("#openPlayInter").hide();
            var defaultOption = data.defaultOption, //默认选项 根上的字段
                pictureStop = data.pictureStop,
                noComponent = data.noComponent, //是否有组件
                selSum = $("#selComponent p"), //所有的选项p
                timer = null,
                TPplayUrl = data.TPplayUrl, // 备课教案
                labelInfo = data.labelInfo;
            $("#labelComponent").remove();
            preVideo.attr("src", data.playUrl).css("display", "block");
            selSum.css("display", "none");
        }
        $("#previewVideo").show(200);
        // 因为每一次结束时，会改变video的src，所以上一个监听的src视频地址是还存在的，所以再每次加监听时，先去除上一个视频的监听。
        preVideo.unbind('play').bind('play', function () {
            // console.log("开始"); //开始播放时会将选项全部隐藏
            preVideo.attr("controls", "true");
            selSum.css("display", "none");
            /**
             * 备课教案组件
             * @TPplayUrl 备课教案视频的播放地址
             */
            if (TPplayUrl) {
                $("#teachVideo").css("display", "block").attr("src", TPplayUrl);
            } else {
                $("#teachVideo").css("display", "none");
            }
            if (!children || children.length == 0) {
                return false
            }
            interGame = children[0].interGame
            /**
             * 备课教案组件完成  
             *   ***问题视频音频重合
             */
        })
        preVideo.unbind('pause').bind('pause', function () {
            // console.log('暂停');
        })
        preVideo.unbind('ended').bind('ended', function () {
            console.log("结束"); //结束后判断此视频分支有几个，对应的渲染选项个数
            // pictureStop画面暂停组件  defaultOption倒计时默认选项组件
            if (!children || children.length === 0) {
                console.log("视频播放结束且当前视频后已无分支视频");
                // children = data.children;
                // preVideo.attr("src", data.playUrl);
                // preVideo.trigger('pause');
                return false;
            }
            /**
             * 判断下一分支是否是ai互动
             */
            // console.log(interGame);
            if (interGame) {
                // preVideo.hide();
                // let interGame = children[0].interGame;
                preVideo.trigger('pause');
                $("#openPlayInter").attr('src', `../studentPort/playInterGame.html?type=${interGame._interType}&_interId=${interGame._interId}`);
                $("#openPlayInter").show();
                $(window).unbind("message").on("message", function (e) {
                    e.preventDefault();
                    // alert(JSON.stringify(e.originalEvent.data));
                    if (e.originalEvent.data) {
                        children = children[0].children;
                        console.log(children);
                        if (children.length == 0) {
                            console.log("互动播放结束，最后分支为ai互动");
                            return false
                        }
                        children[0].interGame ? interGame = children[0].interGame : interGame = "";
                        if (interGame) {
                            // preVideo.hide();
                            // let interGame = children[0].interGame;
                            $("#openPlayInter").attr('src', `../studentPort/playInterGame.html?type=${interGame._interType}&_interId=${interGame._interId}`);
                            $("#openPlayInter").show();
                            $(window).unbind("message").on("message", function (e) {
                                e.preventDefault();
                                // alert(JSON.stringify(e.originalEvent.data));
                                if (e.originalEvent.data) {
                                    children = children[0].children;
                                    if (children.length == 0) {
                                        return false
                                    }

                                    console.log(children);
                                    defaultOption = children[0].defaultOption; //默认选项 根上的字段
                                    pictureStop = children[0].pictureStop;
                                    noComponent = children[0].noComponent; //是否有组件
                                    TPplayUrl = children[0].TPplayUrl; // 备课教案
                                    labelInfo = children[0].labelInfo;
                                    let playUrl = children[0].playUrl;
                                    children = children[0].children;
                                    $("#openPlayInter").hide();
                                    preVideo.attr("src", playUrl).css("display", "block");
                                }
                            });
                            return false;
                        };
                        console.log(children);
                        defaultOption = children[0].defaultOption; //默认选项 根上的字段
                        pictureStop = children[0].pictureStop;
                        noComponent = children[0].noComponent; //是否有组件
                        TPplayUrl = children[0].TPplayUrl; // 备课教案
                        labelInfo = children[0].labelInfo;
                        let playUrl = children[0].playUrl;
                        children = children[0].children;
                        $("#openPlayInter").hide();
                        preVideo.attr("src", playUrl).css("display", "block");
                    }
                });
                return false;
            }
            preVideo.removeAttr("controls"); //暂停选择下一分支时，将视频控件删除（隐藏实现不了，所以只能删除属性）
            /**
             * 无组件 直接播放下个分支
             *  ai互动字段的赋值 放在了视频播放开始的事件中
             */
            if (noComponent) {
                // console.log(children);
                let playUrl = children[0].playUrl;
                pictureStop = children[0].pictureStop;
                defaultOption = children[0].defaultOption; //因为代码进行到这里证明播放下个分支视频了，所以需要将倒计时进行重新赋值，赋值为要播放分支得defaultOption
                // console.log(children[0].defaultOption);
                noComponent = children[0].noComponent;
                TPplayUrl = children[0].TPplayUrl;
                // console.log(children[0].interGame);
                children[0].labelInfo ? labelInfo = children[0].labelInfo : labelInfo = "";
                // children[0].interGame ? interGame = children[0].interGame : interGame = "";
                // console.log(interGame);
                children = children[0].children;
                console.log("noComponent---------------");
                console.log("无组件" + labelInfo);
                preVideo.attr("src", playUrl);
                return false;
            }
            /**
             * 无组件 直接播放下个分支 结束
             */
            /**
             * 标注组件 直接播放下个分支 
             */
            // console.log(labelInfo);
            if (labelInfo) { //labelComponent
                $("#labelComponent").remove();
                let clickNum = 0;
                let zimu = "";
                let cloneEle = $("#setLabelImg").clone().attr({
                    "id": "labelComponent",
                });
                cloneEle.find("img").attr("src", labelInfo.labelBackgroundImg);
                preVideo.css({
                    display: "none"
                })
                $("#previewVideo .centerBox").append(cloneEle);
                $("#labelComponent .setLabel").remove();
                for (let i = 0; i < labelInfo.num; i++) {
                    console.log(labelInfo.num);
                    if (i == 0) {
                        zimu = "A";
                    } else if (i == 1) {
                        zimu = "B";
                    } else if (i == 2) {
                        zimu = "C";
                    } else if (i == 3) {
                        zimu = "D";
                    }
                    $("#labelComponent").append(`
                    <div class="setLabel label${zimu}" style="left:${labelInfo.x[i]};top:${labelInfo.y[i]};transform:rotate(${labelInfo.rotate[i]}deg)">
                    <em class="iconfont icondian"></em>
                    <i></i>
                        <p>${labelInfo.textInfo[i]}</p>
                    </div>
                    `);
                }
                $("#labelComponent").unbind("click").click(function (e) {
                    e.preventDefault();
                    if (clickNum >= 5) { //大于5 跳下个分支
                        let playUrl = children[0].playUrl;
                        pictureStop = children[0].pictureStop;
                        defaultOption = children[0].defaultOption; //因为代码进行到这里证明播放下个分支视频了，所以需要将倒计时进行重新赋值，赋值为要播放分支得defaultOption
                        // console.log(children[0].defaultOption);
                        noComponent = children[0].noComponent;
                        TPplayUrl = children[0].TPplayUrl;
                        children[0].labelInfo ? labelInfo = children[0].labelInfo : labelInfo = "";
                        console.log("标注组件" + labelInfo);
                        children = children[0].children;
                        $(this).css("display", "none");
                        preVideo.css("display", "block");
                        preVideo.attr("src", playUrl);
                    }
                    clickNum++;
                });
                return false;
            }
            /**
             * 标注组件 直接播放下个分支 结束
             */
            /**
             * 画面暂停组件
             */
            if (pictureStop == 1) {
                let picStopBtn = $("#picStopBtn")
                picStopBtn.css("display", "block");
                picStopBtn.unbind("click").bind("click", function () {
                    picStopBtn.css("display", "none");
                    let playUrl = children[0].playUrl;
                    pictureStop = children[0].pictureStop;
                    defaultOption = children[0].defaultOption; //因为代码进行到这里证明播放下个分支视频了，所以需要将倒计时进行重新赋值，赋值为要播放分支得defaultOption
                    // console.log(children[0].defaultOption);
                    noComponent = children[0].noComponent;
                    TPplayUrl = children[0].TPplayUrl;
                    children[0].labelInfo ? labelInfo = children[0].labelInfo : labelInfo = "";
                    console.log("画面暂停" + labelInfo);
                    children = children[0].children;
                    preVideo.attr("src", playUrl);
                })
                return false;
            }
            /**
             * 画面暂停组件结束
             */
            /**
             * 视频结束，判断加载选项个数
             */
            if (children.length === 1) {
                $("#preSelA").css({
                    left: "27.5%",
                    bottom: '12%'
                });
                $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
            } else if (children.length === 2) {
                selSum.css({
                    width: "40%"
                });
                $("#preSelA").css({
                    bottom: '12%',
                    left: "7%"
                });
                $("#preSelB").css({
                    bottom: '12%',
                    left: "52%"
                });
                $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                $("#preSelB").css("display", "block").text(children[1].answerName).attr("treeId", children[1].id);
            } else if (children.length === 3) {
                selSum.css({
                    width: "25%"
                });
                $("#preSelA").css({
                    left: "7%",
                    bottom: '12%'
                });
                $("#preSelB").css({
                    left: "37%",
                    bottom: '12%'
                });
                $("#preSelC").css({
                    left: "67%",
                    bottom: '12%'
                });
                $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                $("#preSelB").css("display", "block").text(children[1].answerName).attr("treeId", children[1].id);
                $("#preSelC").css("display", "block").text(children[2].answerName).attr("treeId", children[2].id);
            } else if (children.length === 4) {
                selSum.css({
                    width: "40%"
                });
                $("#preSelA").css({
                    left: "7%",
                    bottom: '24%'
                });
                $("#preSelB").css({
                    left: "52%",
                    bottom: '24%'
                });
                $("#preSelC").css({
                    bottom: '12%',
                    left: "7%"
                });
                $("#preSelD").css({
                    bottom: '12%',
                    left: "52%"
                });
                $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                $("#preSelB").css("display", "block").text(children[1].answerName).attr("treeId", children[1].id);
                $("#preSelC").css("display", "block").text(children[2].answerName).attr("treeId", children[2].id);
                $("#preSelD").css("display", "block").text(children[3].answerName).attr("treeId", children[3].id);
            }
            /**
             * 视频结束，判断加载选项个数结束
             */
            /**
             * 倒计时默认选项组件
             */
            if (defaultOption) {
                console.log("倒计时默认选项开始了");
                timer = setTimeout(() => {
                    selSum.css("display", "none");
                    //点击某一个选项时，获取这个选项的上的treeId，用此字段去调用G6的方法，查找其树叉的数据信息
                    let dataInfo = graph.findDataById(defaultOption); //g6api  通过数据中某一个数据的id 过去数据本身
                    defaultOption = dataInfo.defaultOption; //将播放的树叉的默认选项字段加给他
                    noComponent = dataInfo.noComponent;
                    pictureStop = dataInfo.pictureStop;
                    TPplayUrl = dataInfo.TPplayUrl;
                    dataInfo.labelInfo ? labelInfo = dataInfo.labelInfo : labelInfo = "";
                    console.log("倒计时" + labelInfo);
                    children = dataInfo.children;
                    // console.log(children);
                    preVideo.attr("src", dataInfo.playUrl);
                }, 5000);
            }
            /**
             * 倒计时默认选项组件结束
             */
            /**
             * 选项卡点击组件
             */
            selSum.unbind("click").click(function (e) {
                e.preventDefault();
                clearTimeout(timer);
                selSum.css("display", "none");
                //点击某一个选项时，获取这个选项的上的treeId，用此字段去调用G6的方法，查找其树叉的数据信息
                let treeId = $(this).attr("treeId");
                let dataInfo = graph.findDataById(treeId); //g6api  通过数据中某一个数据的id 过去数据本身
                // console.log(dataInfo);
                children = dataInfo.children;
                pictureStop = dataInfo.pictureStop;
                noComponent = dataInfo.noComponent;
                TPplayUrl = dataInfo.TPplayUrl;
                dataInfo.labelInfo ? labelInfo = dataInfo.labelInfo : labelInfo = "";
                console.log("点击组件" + labelInfo);
                defaultOption = dataInfo.defaultOption; //将播放的树叉的默认选项字段加给他
                preVideo.attr("src", dataInfo.playUrl);
            });
            /**
             * 选项卡点击组件结束
             */
        })
        console.groupEnd();
    });
    $("#teachVideo").unbind('play').bind('play', function () {
        $(this).css("z-index", "1000");
        $("#preVideo").trigger('pause');
    });
    $("#teachVideo").unbind('ended').bind('ended', function () {
        $(this).css("z-index", "1");
        $("#preVideo").trigger("play");
    });
    // chrome浏览器全屏事件监听
    document.addEventListener("webkitfullscreenchange", function (e) {
        // console.log(e)  //target: video#preVideo  返回的是元素 所以不能当作字符串用
        if (document.fullscreenElement || document.webkitFullscreenElement) {
            isFullScreen = true;
            $("#commitDialog").show(100).find("#commitAfterText").text("禁止全屏");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
        } else {
            isFullScreen = false;
        }
    });
    document.addEventListener("mozfullscreenchange", function (e) {
        // console.log(e);
        // 判断是否处于全屏
        if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
            isFullScreen = true;
            $("#commitDialog").show(100).find("#commitAfterText").text("禁止全屏");
            setTimeout(function () {
                $("#commitDialog").hide(100);
            }, 1000)
        } else {
            isFullScreen = false;
        }
    });
    // picturePause 画面暂停组件的switch滑动按钮
    $("#switchBtn").click(function (e) {
        e.preventDefault();
        let bool = $(this).attr("clickBool"); // 0-false 1-true
        if (bool == '0') {
            $(this).find("span").css({
                'border-color': 'rgba(51, 185, 248, 1)',
                'background-color': 'rgba(51, 185, 248, 1)'
            }).find("i").css({
                left: '100%',
                marginLeft: "-44%"
            })
            bool = 1;
            $(this).attr("clickBool", bool);
        } else {
            $(this).find("span").css({
                'border-color': '#dcdfe6',
                'background-color': '#dcdfe6'
            }).find("i").css({
                left: '2%',
                marginLeft: "0"
            })
            bool = 0;
            $(this).attr("clickBool", bool);
        }
    });

    /**  2100 2-2hao ai游戏  (互动素材赋值给树杈上只能拖拽方法)
     *  
     * @vidMaterial 视频素材 点击隐藏下方ul列表
     * @interMaterial ai互动素材
     * @getInterGame  上传互动视频按钮 点击显示弹窗
     * @ $("#InterType") 展示活动类型列表，点击li对应渲染类型下的互动列表
     */
    $("#getInterGame").click(function (e) {
        e.preventDefault();
        $("#addInterGDia").show(200);
    });
    // $("#vidMaterial").click(function (e) {
    //     e.preventDefault();
    //     $("#materialStore").slideToggle(200);
    // });
    $("#interMaterial").click(function (e) {
        e.preventDefault();
        $("#interMaterStore").slideToggle(200);
    });
    $("#InterType").click(function () {
        $("#showInterType").slideToggle(200);
        $("#showInterType li").unbind("click").click(function (e) {
            e.preventDefault();
            $("#InterType").text($(this).text());
            $("#showInterType").slideUp(200);
            let type = $(this).attr("type");
            let data = {
                type,
                page: 1,
                row: 15
            }
            $.ajax({
                type: "get",
                url: `${testUrl}/S9vC7rYOo4.php/small/resource/type`,
                data: data,
                success: function (res) {
                    $("#showInterName").empty();
                    let eleArr = '';
                    $.each(res.data.rows, function (i, item) {
                        if (item.title) { //过滤一下名为空不加载
                            eleArr += `<li _interId="${item.id}">${item.title}</li>`
                        }
                    });
                    $("#showInterName").append(eleArr);
                }
            });
        });
    })
    /** 点击ai课程的列表弹窗，点击里面li利用InterId获取对应ai互动数据
     *  @dragInterMaterial( )   函数使素材库中添加的互动素材可以被拖拽
     */
    function dragInterMaterial() {
        // ：jQuery中的click事件会累计绑定（导致会多次触发造成卡顿）所以我们可以在下次点击前先解绑jq绑定事件
        /**  当分支增多时会造成卡顿 
         *   graph.data(data);
                    graph.render();
                    graph.fitView();
         */
        $("#materialStore li.dragInterStyle").unbind().bind("mousedown", function (event) {
            // if (!$(this).attr("_interId")) {
            //     return false
            // }
            console.group("互动素材拖拽参数");
            event.preventDefault();
            let moveEle = $(this).clone().attr("id", "rootEle"); //rootEle id 是为了给克隆的移动元素加一些样式
            $("body").append(moveEle);
            let distanceCliX = event.clientX;
            let distanceCliY = event.clientY;
            let mouseEnterTimer = null;
            let id = ""; //树杈的id
            let _interId = $(this).attr("_interId"),
                _interType = $(this).attr("_interType"),
                _interImg = $(this).find("img").attr("src"),
                _interTitle = $(this).find("p").text();
            $("body>.dragInterStyle").css({
                left: distanceCliX - 50 + "px",
                top: distanceCliY - 30 + "px"
            });
            $("body").unbind("mousemove").mousemove(function (e) {
                e.stopPropagation();
                var offX = e.clientX;
                var offY = e.clientY;
                $("body>.dragInterStyle").css({
                    left: offX - 50,
                    top: offY - 10
                })
                $("svg section").mouseenter(function (e2) { //移动到某一个树叉的元素范围内，获取这个树叉的id字段
                    e2.stopPropagation();
                    mouseEnterTimer = setTimeout(() => {
                        //只有拖到树叉上并且停留了300ms后才会去获取此互动素材的id
                        id = $(this).attr("id");
                        that = this;
                    }, 300);
                });
            }).unbind("mouseup").mouseup(function (e1) {
                e1.stopPropagation();
                clearTimeout("mouseEnterTimer");
                if (id) {
                    let info = graph.findDataById(id);
                    console.log(id, _interId, _interType, _interImg);
                    console.log(info);
                    info.imgUrl = _interImg;
                    info.label = _interTitle;
                    info.interGame = { //只给树杈存放ai互动的数据结构添加info.interGame字段
                        _interId: "",
                        _interType: ""
                    }
                    info.interGame._interId = _interId;
                    info.interGame._interType = _interType;
                    graph.updateChild(info, id);
                    graph.render();
                    graph.fitView();
                }
                $(".storyLineOpt").hide();
                console.log("清除");
                console.groupEnd();
                $("body").unbind();
                $("body>.dragInterStyle").remove();
            });
        });
    }
    $("#showInterName").on("click", "li", function (e) {
        let _interId = $(this).attr("_interId");
        $.ajax({
            type: "get",
            url: `${testUrl}/S9vC7rYOo4.php/small/resource/edit?id=${_interId}`,
            success: function (res) {
                $("#materialStore").append(`<li class="dragInterStyle" _interId="${res.data.id}" _interType="${res.data.type}">
                <div class="conBox">
                    <img draggable="false" src="${res.data.cover}">
                </div>
                <p>${res.data.title}</p>
            </li>`)
                dragInterMaterial(); //拖拽 移入 
            }
        });
    });
    /**  iframe标签渲染的子页面 向其父页面传参
     *   父页面通过监听 message来获取参数
     */
})